package jsf;

import java.io.Serializable;
import java.util.ArrayList;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import util.SessionUtil;
import ejb.UsersBeanRemote;
import entity.Users;

@RequestScoped
@ManagedBean
public class UsersController implements Serializable {

	private static final long serialVersionUID = 1L;
	@EJB(lookup="java:global/EnrollmentManagementEAP/EnrollmentManagementEJB/UsersBean!ejb.UsersBeanRemote")
	UsersBeanRemote bean;
	private Long selectedId;
	private boolean isActive;
	private ArrayList<Users> users = new ArrayList<Users>();
	private Users user = new Users();
	public UsersController() {
		SessionUtil.authenticate();
	}
	
	public ArrayList<Users> getUsers() {
		ArrayList<Users> users = new ArrayList<Users>();
		users.addAll(bean.getAll());
		this.users = users;
		return this.users;
	}
	
	public boolean isActive() {
		return this.isActive;
	}
	
	public void setIsActive(boolean isActive) {
		this.isActive = isActive;
	}
	
	public Users getUser() {
		return this.user;
	}
	
	private Long getSelectedId() {
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        return Long.parseLong(context.getRequestParameterMap().get("selectedId"));
    }
	
	public String edit() {
        selectedId = this.getSelectedId();
        if(selectedId != null) {
            this.user = this.bean.get(selectedId);
            return "user.xhtml";
        }
        return "users.xhtml";
    }
	
	// For Index Form
	public String create() {
		this.selectedId = null;
        this.user = new Users();
        return "user.xhtml";
    }
	
	// For Edit Form
	public String doSubmit() {
        if(selectedId == null) {
            return this.doCreate();
        } else {
            return this.doEdit();
        }
    }
	
	// For Edit Form
	public String doEdit() {
        this.bean.update(this.user);
        return "users.xhtml";
    }
    
	// For Edit Form
    public String doCreate() {
    	this.bean.insert(this.user);
        return "users.xhtml";
    }
	
    // For Index Form
	public void doDelete() {
        Long selectedId = this.getSelectedId();
        Users selectedUser = this.bean.get(selectedId);
        if(selectedUser != null) {
            this.bean.delete(selectedUser);
        }
    }
}
